#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
电脑自动关机脚本
功能：根据不同操作系统执行关机命令
"""

import os
import platform
import time
import sys

def print_with_color(text, color="default"):
    """打印带颜色的文本"""
    colors = {
        "red": "\033[91m",
        "green": "\033[92m",
        "yellow": "\033[93m",
        "blue": "\033[94m",
        "default": "\033[0m"
    }
    
    # Windows系统不支持ANSI颜色代码，直接打印文本
    if platform.system() == "Windows":
        print(text)
    else:
        print(f"{colors.get(color, colors['default'])}{text}{colors['default']}")

def shutdown_computer(delay=0):
    """
    关闭计算机
    
    参数:
        delay: 延迟关机的秒数
    """
    # 获取操作系统类型
    system = platform.system()
    
    print_with_color("======================================", "blue")
    print_with_color("         电脑自动关机脚本         ", "blue")
    print_with_color("======================================", "blue")
    
    if delay > 0:
        print_with_color(f"电脑将在 {delay} 秒后关机...", "yellow")
        time.sleep(delay)
    else:
        print_with_color("准备执行关机操作...", "yellow")
    
    try:
        if system == "Windows":
            # Windows系统关机命令
            os.system("shutdown /s /t 0")
        elif system == "Darwin":  # macOS
            # macOS系统关机命令
            os.system("sudo shutdown -h now")
        elif system == "Linux":
            # Linux系统关机命令
            os.system("sudo shutdown -h now")
        else:
            print_with_color(f"不支持的操作系统: {system}", "red")
            return False
        
        return True
    except Exception as e:
        print_with_color(f"关机过程中发生错误: {str(e)}", "red")
        return False

def main():
    """主函数"""
    # 检查是否有管理员/root权限（在Windows上）
    if platform.system() == "Windows":
        import ctypes
        is_admin = ctypes.windll.shell32.IsUserAnAdmin() != 0
        if not is_admin:
            print_with_color("请以管理员身份运行此脚本！", "red")
            print_with_color("正在尝试以管理员身份重新启动...", "yellow")
            # 以管理员身份重新启动脚本
            ctypes.windll.shell32.ShellExecuteW(
                None, "runas", sys.executable, " ".join(sys.argv), None, 1
            )
            return 1
    
    # 执行关机操作
    shutdown_computer()
    return 0

if __name__ == "__main__":
    sys.exit(main())